package util.io;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import util.ContestantLap;
import util.TimeData;

/**
 * Imports lap finish and start times
 * @author team07
 *
 */
public class FileImporterLap extends FileImporter {

	private Map<Integer, ContestantLap> map = new HashMap<Integer, ContestantLap>();

	/**
	 * Loads finish times from the specified strings. Overridden method from the
	 * superclass
	 * 
	 * @param fileName
	 *            The file to be parsed
	 * @throws IOException
	 *             If the file cannot be found or similiar.
	 */
	@Override
	protected void loadFinish(String fileName) throws IOException {
		ArrayList<String> fileLines = super.loadData(fileName);
		IdTimePair[] pairs = super.parseTime(fileLines);
		for (IdTimePair pair : pairs) {
			ContestantLap c = getContestant(pair.id);
			c.addFinishTime(pair.ms);
		}
	}

	/**
	 * Loads start times from the specified strings. Overridden method from the
	 * superclass
	 * 
	 * @param fileName
	 *            The file to be parsed
	 * @throws IOException
	 *            If the file cannot be found or similiar.
	 */
	@Override
	protected void loadStart(String fileName) throws IOException {
		ArrayList<String> fileLines = super.loadData(fileName);
		IdTimePair[] pairs = super.parseTime(fileLines);
		for (IdTimePair pair : pairs) {
			ContestantLap c = getContestant(pair.id);
			c.addStartTime(pair.ms);
		}
	}

	/**
	 * Constructs a new TimeData object from the local map that is being used in
	 * this instance of the class. Overridden method from the superclass
	 * 
	 * @return The TimeData object.
	 */
	@Override
	public TimeData getData() {
		TimeData td = new TimeData();
		td.setNewNameIdientifier(data.getNewNameIdientifier());
		td.putAllContestants(map);
		return td;
	}

	/**
	 * This function mirrors the getContestant() in the super class, since the
	 * super class function has the wrong type.
	 * 
	 * @param id
	 *            The id to look for
	 * @return The contestant
	 */
	protected ContestantLap getContestant(int id) {
		ContestantLap c = map.get(id);

		if (c == null) {
			c = new ContestantLap(id);
			map.put(c.getID(), c);
		}
		return c;
	}
}
